import cv,sys
import os
s=[]
feature=''
feature_idx=0
point =[0,0]
from optparse import OptionParser

def getParser():
    parser = OptionParser()
    parser.add_option("-d", "--features", dest = "features", type ="string", default = "")
    parser.add_option("-f", "--filename", dest = "filename", type = "string", default = "")
    return parser



def ReadFeaturesToFindFile(filename):
	
	featurepoints =['none'];

	txt = open(filename, "r")
	
	line = txt.readline()
	
	featurepoints.remove('none')
	nofeatures = int(line)
	
	for i in range(nofeatures):
		
		line = txt.readline()
		featurepoints.append((line.split()[0],float(line.split()[1]),float(line.split()[2])))


	return featurepoints	
def my_mouse_callback(  event,  x,  y,  flags,  param ):
	

	if( event ==   cv.CV_EVENT_LBUTTONUP):
		s[feature_idx] = feature + ' '+str(x) +' '+str(y)
		point[0] =x
		point[1] = y
		print s[feature_idx]
		print 'Press any key to finalize'
	



if __name__ == '__main__':
	
	parser = getParser()
	(options, args) = parser.parse_args()
	
	print "sys.argv",sys.argv
	if( os.path.exists(options.filename) ):
		print "file exists"

	image = cv.LoadImage(options.filename)

	features= ReadFeaturesToFindFile(options.features)
	s= ['']*(len(features)+1)
	print s

	s[0] = (str(len(features)))
	name =options.filename
	cv.NamedWindow(name );
	temp =cv.CloneImage(image)
	
	# Set up the callback
	cv.SetMouseCallback(name, my_mouse_callback,  temp);

	# Main loop
	colors=[(255,0,0),(255,0,0),(255,0,0),(0,255,0),(0,255,0),(0,255,0),(255,255,0),(255,255,0),(0,0,255),(0,0,255)]
		
	for i in range(len(features)):
		feature_idx=i+1
		feature = features[i][0]
		print 'Choose a coordinate for',features[i][0]
		
		cv.ShowImage(name , temp )

		if( cv.WaitKey( 0 )) :
			print point
			cv.Circle(temp,(point[0],point[1]),3,colors[i])

	cv.ShowImage(name , temp )
	print 'Final Image, press enter to save'
	cv.WaitKey( 0 )

	tmp = os.path.splitext(name)
	user = os.environ['USER']
	
	f = open(tmp[0]+'.data','w')
	f.write("trained by:" + user +"\n")
	
	for i in range(len(s)):
	    f.write(s[i]+' ')
	print s
	f.close()	
